package com.kurumi.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kurumi.config.MyConfig;
import com.kurumi.pojo.MedicalRecord;
import com.kurumi.pojo.RespondResult;
import com.kurumi.pojo.coding_attached.DRGsManageInfo;
import com.kurumi.query.MedicalRecordDRGsQuery;
import com.kurumi.service.BaseInfoService;
import com.kurumi.service.MedicalRecordCodingService;
import com.kurumi.service.MedicalRecordDRGsService;
import com.kurumi.util.DateUtil;
import com.kurumi.util.ExcelUtils;
import com.kurumi.util.FileUtil;
import com.kurumi.util.JsonUtil;
import com.kurumi.util.NumberUtils;
import com.kurumi.util.ObjectUtils;
import com.kurumi.util.StringUtil;

@Controller
@RequestMapping("/drgs_manage")
public class MedicalRecordDRGsManageController {

	@Autowired
	private MyConfig myConfig;

	@Autowired
	private MedicalRecordCodingService medicalRecordCodingService;

	@Autowired
	private MedicalRecordDRGsService medicalRecordDRGsService;

	@Autowired
	private BaseInfoService baseInfoService;

	@GetMapping("/drgs_group_page")
	public String drgsGroupPage(Model model){
		return "drgs_manage/drgs_group_page";
	}

	@GetMapping("/coding_export_page")
	public String codingExportPage(Model model){
		return "drgs_manage/coding_export_page";
	}

	@GetMapping("/import_drgs_group_page")
	public String importDRGSGroupIPage(){
		return "drgs_manage/import_drgs_group_page";
	}

	@GetMapping("/ajax_query_drgs_group")
	@ResponseBody
	public RespondResult ajaxQueryDRGsGroup(MedicalRecordDRGsQuery params){
		RespondResult respondResult = null;

		try{
			List<Map<String,Object>> records = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.IsPropertyEmpty()){
				records = medicalRecordDRGsService.getMedicalRecordOfDRGsGroup(params);
				count = medicalRecordDRGsService.getMedicalRecordCountOfDRGsGroup(params);
			}

			params.setTotalCounts(count);
			params.setDatas(records);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}

		return respondResult;
	}


	@GetMapping("/ajax_query_coding_export")
	@ResponseBody
	public RespondResult ajaxQueryCodingExport(MedicalRecordDRGsQuery params){
		RespondResult respondResult = null;

		try{
			List<Map<String,Object>> records = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.CodingExportEmpty()){
				records = medicalRecordDRGsService.getCodingExport(params);
				count = medicalRecordDRGsService.getCodingExportCount(params);
			}

			params.setTotalCounts(count);
			params.setDatas(records);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}

		return respondResult;
	}

	@ResponseBody
	@GetMapping("/ajax_query_drgs_group_by_id")
	public RespondResult ajaxQueryDRGsGroupById(String visitGuid,Model model){
		RespondResult respondResult = null;

		try{
			List<String> jsonDatas = medicalRecordCodingService.getMedicalRecordJsonByVisitGuid(visitGuid);
			Map<String, Object> drgsManageInfo = null;
			if(!jsonDatas.isEmpty()){
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap = JsonUtil.jsonToPojo(jsonDatas.get(0), Map.class);
				drgsManageInfo = (Map<String, Object>)jsonMap.get("drgsManageInfo");
			}
			if(drgsManageInfo == null){
				drgsManageInfo = new HashMap<String, Object>();
			}
			respondResult = new RespondResult(true, RespondResult.successCode, null, drgsManageInfo);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), visitGuid);
		}
		return respondResult;

	}

	@ResponseBody
	@PostMapping("/ajax_edit_drgs_group")
	public RespondResult ajaxEditDRGsGroup(DRGsManageInfo drgsManageInfo,Model model){
		try{
			String visitGuid = drgsManageInfo.getVisitGuid();
			String filePath = myConfig.getJsonRecourcePath() + StringUtil.getLocalPath(visitGuid)+visitGuid+"\\";
			String versionFilePath =filePath+"version\\";
			String fileName = visitGuid + ".json";
			String versionFileName = visitGuid+"-" + DateUtil.dateFormat("yyyyMMddHHmmssssss", new Date()) + ".json";
			/*String jsonData = FileUtil.readFile(filePath, fileName);*/
			List<String> jsonDatas = medicalRecordCodingService.getMedicalRecordJsonByVisitGuid(visitGuid);
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			if(!jsonDatas.isEmpty()){
				jsonMap = JsonUtil.jsonToPojo(jsonDatas.get(0), Map.class);
				if(jsonMap == null){
					jsonMap = new HashMap<String, Object>();
				}
			}
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			jsonMap.put("userCode", userCode);
			jsonMap.put("userName", userName);
			jsonMap.put("drgsManageInfo", drgsManageInfo);
			String jsonMapJson = JsonUtil.objectToJson(jsonMap);
			FileUtil.createOrEditFile(jsonMapJson, filePath, fileName);
			FileUtil.createOrEditFile(jsonMapJson, versionFilePath, versionFileName);
			int result = medicalRecordCodingService.editDRGsManageInfoInfo(visitGuid, drgsManageInfo, jsonMap);


			if(result > 0){
				return new RespondResult(true, RespondResult.successCode, "DRGs分组成功", "DRGs分组成功");
			}else{
				return new RespondResult(true, RespondResult.errorCode, "DRGs分组失败", "DRGs分组失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return new RespondResult(false, RespondResult.errorCode, e.getMessage(), "DRGs分组失败");
		}
	}

	@GetMapping("/coding_export_excel")
	public void codingExportExcel(MedicalRecordDRGsQuery params,HttpServletResponse response){
		OutputStream out = null;
		try{
			params.setPageSize(null);
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			if(!params.CodingExportEmpty()){
				medicalRecords = medicalRecordDRGsService.getCodingExport(params);
			}
			response.setContentType("applicationnd.ms-excel");
			String title= "编码导出"+DateUtil.dateFormat(new Date());
			StringBuilder downLoadFileName = new StringBuilder();
			downLoadFileName = new StringBuilder(
					"attachment;filename=");
			downLoadFileName.append(title)
					.append(".xls");
			/*downLoadFileName.append(title).append(DateUtil.dateFormat(new Date()))
			.append(".dbf");*/
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			List<String> headers = new ArrayList<String>();
			headers.add("住院号");
			headers.add("出院日期");
			headers.add("出院病区名称");
			headers.add("住院天数");
			headers.add("医生手术操作名称");
			headers.add("主要手术操作编码");
			headers.add("主要诊断名称");
			headers.add("主要诊断编码");
			headers.add("总费用");
			headers.add("手术费用");
			headers.add("医疗资源费用");
			headers.add("新生儿出生体重");
			headers.add("有创呼吸机使用时间（小时）");
			headers.add("重症监护时间（天数）");
			headers.add("我院DRGs分组代码");
			headers.add("本病例DRGs总权重");
			headers.add("是否MDT");
			List<String> keys = new ArrayList<String>();
			keys.add("only_id");
			keys.add("out_hospital_date");
			keys.add("out_dept_name");
			keys.add("in_hospital_day_number");
			keys.add("doctor_operate_name");
			keys.add("main_operate_code");
			keys.add("main_diag_name");
			keys.add("main_diag_code");
			keys.add("total_cost");
			keys.add("operate_cost");
			keys.add("medical_resource_cost");
			keys.add("baby_birth_weight");
			keys.add("medical_ventilator_used_day_number");
			keys.add("intensive_care_day_number");
			keys.add("local_drgs_group_code");
			keys.add("local_drgs_group_total_weight");
			keys.add("mdt_code");
			List<Map<String, String>> records = new ArrayList<Map<String,String>>();
			for (Map<String, Object> medicalRecord : medicalRecords) {
				String visitGuid =( String)medicalRecord.get("visit_guid");
				List<String> jsonDatas = medicalRecordCodingService.getMedicalRecordJsonByVisitGuid(visitGuid);

				Map<String, String> record = new HashMap<String, String>();
				record.put("only_id",(String)medicalRecord.get("only_id"));
				record.put("out_hospital_date",(String)medicalRecord.get("out_hospital_date_format"));
				record.put("out_dept_name",(String)medicalRecord.get("out_dept_name"));
				BigDecimal medicalResourceCost = BigDecimal.ZERO;
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				if(!jsonDatas.isEmpty()){
					jsonMap = JsonUtil.jsonToPojo(jsonDatas.get(0), Map.class);
					Map<String, Object> basicInfo = (Map<String, Object>)jsonMap.get("basicInfo");
					Map<String, Object> cureInfo = (Map<String, Object>)jsonMap.get("cureInfo");
					Map<String, Object> diseaseDiagInfo = (Map<String, Object>)jsonMap.get("hqmsDiseaseDiagInfo");
					Map<String, Object> operateInfo = (Map<String, Object>)jsonMap.get("hqmsOperateInfo");
					Map<String, Object> intensiveCareInfo = (Map<String, Object>)jsonMap.get("intensiveCareInfo");
					Map<String, Object> medicalVentilatorInfo = (Map<String, Object>)jsonMap.get("medicalVentilatorInfo");
					Map<String, Object> costInfo = (Map<String, Object>)jsonMap.get("costInfo");

					if(basicInfo != null){
						Object inHospitalDayNumber = basicInfo.get("inHospitalDayNumber");
						if(inHospitalDayNumber != null){
							record.put("in_hospital_day_number",""+(Integer)inHospitalDayNumber);
						}
					}
					if(operateInfo != null){
						List<Map<String, Object>> operateRecords = (List<Map<String, Object>>)operateInfo.get("operateRecords");
						if(!operateRecords.isEmpty()){
							Map<String, Object> operateRecord = operateRecords.get(0);
							Object operateOriginalDesc = operateRecord.get("operateOriginalDesc");
							if(operateOriginalDesc != null){
								record.put("doctor_operate_name",(String)operateOriginalDesc);
							}
							Object operateCode = operateRecord.get("operateCode");
							if(operateCode != null){
								record.put("main_operate_code",(String)operateCode);
							}
						}

					}
					if(diseaseDiagInfo != null){
						Map<String, Object> mainDiagRecord = (Map<String, Object>)diseaseDiagInfo.get("mainDiagRecord");
						if(mainDiagRecord != null){

							Object diseaseDiagCode = mainDiagRecord.get("diseaseDiagCode");
							if(diseaseDiagCode != null){
								record.put("main_diag_code",(String)diseaseDiagCode);
							}


							Object diseaseDiagName = mainDiagRecord.get("diseaseDiagName");
							if(diseaseDiagName != null){
								record.put("main_diag_name",(String)diseaseDiagName);
							}
						}
					}

					if(costInfo != null){
						Object totalCost = costInfo.get("totalCost");
						if(totalCost != null){
							record.put("total_cost",""+getBigDecimalValue(totalCost).doubleValue());
						}

						List<Map<String, Object>> costRecords = (List<Map<String, Object>>)costInfo.get("costRecords");
						for (Map<String, Object> costRecord : costRecords) {
							Object medicalCostTypeCode = costRecord.get("medicalCostTypeCode");
							Object costMoney = costRecord.get("costMoney");
							 if(("C03005").equalsIgnoreCase((String)medicalCostTypeCode)){
								if(costMoney != null){
									record.put("operate_cost",""+getBigDecimalValue(costMoney).doubleValue());
								}
							 }else if(("C06001").equalsIgnoreCase((String)medicalCostTypeCode)){
								if(costMoney != null){
									medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								}
							 }else if(("C07001").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C07002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09001").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09003").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C02002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C02003").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }
						}

					}

					if(cureInfo != null){
						Object babyBirthWeight = cureInfo.get("babyBirthWeight");
						if(babyBirthWeight != null){
							record.put("baby_birth_weight",""+getIntegerValue(babyBirthWeight));

						}
					}
					if(medicalVentilatorInfo != null){
						Object medicalVentilatorUsedHourNumber = medicalVentilatorInfo.get("medicalVentilatorUsedHourNumber");
						if(medicalVentilatorUsedHourNumber != null){
							record.put("medical_ventilator_used_day_number",""+getBigDecimalValue(medicalVentilatorUsedHourNumber).floatValue());

						}
					}
					if(intensiveCareInfo != null){
						Object intensiveCareDayNumber = intensiveCareInfo.get("intensiveCareDayNumber");
						if(intensiveCareDayNumber != null){
							record.put("intensive_care_day_number",""+getBigDecimalValue(intensiveCareDayNumber).floatValue());

						}
					}



				}
				record.put("medical_resource_cost",medicalResourceCost.floatValue()+"");
				record.put("local_drgs_group_code",null);
				record.put("local_drgs_group_total_weight",null);
				record.put("mdt_code","否");


				records.add(record);
			}
			ExcelUtils.exportExcel1(out,headers, keys, records);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}


	@GetMapping("/drgs_export_excel")
	public void drgsExportExcel(MedicalRecordDRGsQuery params,HttpServletResponse response){
		OutputStream out = null;
		try{
			params.setPageSize(null);
			List<Map<String,Object>> medicalRecords = new ArrayList<Map<String,Object>>();
			if(!params.IsPropertyEmpty()){
				medicalRecords = medicalRecordDRGsService.getMedicalRecordOfDRGsGroup(params);
			}
			response.setContentType("applicationnd.ms-excel");
			String title= "DRGs导出"+DateUtil.dateFormat(new Date());
			StringBuilder downLoadFileName = new StringBuilder();
			downLoadFileName = new StringBuilder(
					"attachment;filename=");
			downLoadFileName.append(title)
					.append(".xls");
			/*downLoadFileName.append(title).append(DateUtil.dateFormat(new Date()))
			.append(".dbf");*/
			String encodeStr = new String(downLoadFileName.toString().getBytes(
					"GB2312"), "ISO_8859_1");
			response.addHeader("Content-Disposition", encodeStr);
			out = response.getOutputStream();
			List<String> headers = new ArrayList<String>();
			headers.add("住院号");
			headers.add("出院日期");
			headers.add("出院病区名称");
			headers.add("住院天数");
			headers.add("医生手术操作名称");
			headers.add("主要手术操作编码");
			headers.add("主要诊断名称");
			headers.add("主要诊断编码");
			headers.add("总费用");
			headers.add("手术费用");
			headers.add("医疗资源费用");
			headers.add("新生儿出生体重");
			headers.add("有创呼吸机使用时间（小时）");
			headers.add("重症监护时间（天数）");
			headers.add("我院DRGs分组代码");
			headers.add("本病例DRGs总权重");
			headers.add("是否MDT");
			List<String> keys = new ArrayList<String>();
			keys.add("only_id");
			keys.add("out_hospital_date");
			keys.add("out_dept_name");
			keys.add("in_hospital_day_number");
			keys.add("doctor_operate_name");
			keys.add("main_operate_code");
			keys.add("main_diag_name");
			keys.add("main_diag_code");
			keys.add("total_cost");
			keys.add("operate_cost");
			keys.add("medical_resource_cost");
			keys.add("baby_birth_weight");
			keys.add("medical_ventilator_used_day_number");
			keys.add("intensive_care_day_number");
			keys.add("local_drgs_group_code");
			keys.add("local_drgs_group_total_weight");
			keys.add("mdt_code");
			List<Map<String, String>> records = new ArrayList<Map<String,String>>();
			for (Map<String, Object> medicalRecord : medicalRecords) {
				String visitGuid =( String)medicalRecord.get("visit_guid");
				List<String> jsonDatas = medicalRecordCodingService.getMedicalRecordJsonByVisitGuid(visitGuid);

				Map<String, String> record = new HashMap<String, String>();
				record.put("only_id",(String)medicalRecord.get("only_id"));
				record.put("out_hospital_date",(String)medicalRecord.get("out_hospital_date_format"));
				record.put("out_dept_name",(String)medicalRecord.get("out_dept_name"));
				BigDecimal medicalResourceCost = BigDecimal.ZERO;
				Map<String, Object> jsonMap = new HashMap<String, Object>();
				if(!jsonDatas.isEmpty()){
					jsonMap = JsonUtil.jsonToPojo(jsonDatas.get(0), Map.class);
					Map<String, Object> basicInfo = (Map<String, Object>)jsonMap.get("basicInfo");
					Map<String, Object> cureInfo = (Map<String, Object>)jsonMap.get("cureInfo");
					Map<String, Object> diseaseDiagInfo = (Map<String, Object>)jsonMap.get("hqmsDiseaseDiagInfo");
					Map<String, Object> operateInfo = (Map<String, Object>)jsonMap.get("hqmsOperateInfo");
					Map<String, Object> intensiveCareInfo = (Map<String, Object>)jsonMap.get("intensiveCareInfo");
					Map<String, Object> medicalVentilatorInfo = (Map<String, Object>)jsonMap.get("medicalVentilatorInfo");
					Map<String, Object> costInfo = (Map<String, Object>)jsonMap.get("costInfo");
					Map<String, Object> drgsManageInfo = (Map<String, Object>)jsonMap.get("drgsManageInfo");

					if(basicInfo != null){
						Object inHospitalDayNumber = basicInfo.get("inHospitalDayNumber");
						if(inHospitalDayNumber != null){
							record.put("in_hospital_day_number",""+(Integer)inHospitalDayNumber);
						}
					}
					if(operateInfo != null){
						List<Map<String, Object>> operateRecords = (List<Map<String, Object>>)operateInfo.get("operateRecords");
						if(!operateRecords.isEmpty()){
							Map<String, Object> operateRecord = operateRecords.get(0);
							Object operateOriginalDesc = operateRecord.get("operateOriginalDesc");
							if(operateOriginalDesc != null){
								record.put("doctor_operate_name",(String)operateOriginalDesc);
							}
							Object operateCode = operateRecord.get("operateCode");
							if(operateCode != null){
								record.put("main_operate_code",(String)operateCode);
							}
						}

					}
					if(diseaseDiagInfo != null){
						Map<String, Object> mainDiagRecord = (Map<String, Object>)diseaseDiagInfo.get("mainDiagRecord");
						if(mainDiagRecord != null){

							Object diseaseDiagCode = mainDiagRecord.get("diseaseDiagCode");
							if(diseaseDiagCode != null){
								record.put("main_diag_code",(String)diseaseDiagCode);
							}


							Object diseaseDiagName = mainDiagRecord.get("diseaseDiagName");
							if(diseaseDiagName != null){
								record.put("main_diag_name",(String)diseaseDiagName);
							}
						}
					}

					if(costInfo != null){
						Object totalCost = costInfo.get("totalCost");
						if(totalCost != null){
							record.put("total_cost",""+getBigDecimalValue(totalCost).doubleValue());
						}

						List<Map<String, Object>> costRecords = (List<Map<String, Object>>)costInfo.get("costRecords");
						for (Map<String, Object> costRecord : costRecords) {
							Object medicalCostTypeCode = costRecord.get("medicalCostTypeCode");
							Object costMoney = costRecord.get("costMoney");
							 if(("C03005").equalsIgnoreCase((String)medicalCostTypeCode)){
								if(costMoney != null){
									record.put("operate_cost",""+getBigDecimalValue(costMoney).doubleValue());
								}
							 }else if(("C06001").equalsIgnoreCase((String)medicalCostTypeCode)){
								if(costMoney != null){
									medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								}
							 }else if(("C07001").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C07002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09001").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C09003").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C02002").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }else if(("C02003").equalsIgnoreCase((String)medicalCostTypeCode)){
								 if(costMoney != null){
									 medicalResourceCost = medicalResourceCost.add(getBigDecimalValue(costMoney));
								 }
							 }
						}

					}

					if(cureInfo != null){
						Object babyBirthWeight = cureInfo.get("babyBirthWeight");
						if(babyBirthWeight != null){
							record.put("baby_birth_weight",""+getIntegerValue(babyBirthWeight));

						}
					}
					if(medicalVentilatorInfo != null){
						Object medicalVentilatorUsedHourNumber = medicalVentilatorInfo.get("medicalVentilatorUsedHourNumber");
						if(medicalVentilatorUsedHourNumber != null){
							record.put("medical_ventilator_used_day_number",""+getBigDecimalValue(medicalVentilatorUsedHourNumber).floatValue());

						}
					}
					if(intensiveCareInfo != null){
						Object intensiveCareDayNumber = intensiveCareInfo.get("intensiveCareDayNumber");
						if(intensiveCareDayNumber != null){
							record.put("intensive_care_day_number",""+getBigDecimalValue(intensiveCareDayNumber).floatValue());

						}
					}

					if(drgsManageInfo!= null){
						String localDRGsCode = ObjectUtils.getStringValue(drgsManageInfo.get("localDRGsCode"));
						BigDecimal localDRGsGroupTotalWeight = ObjectUtils.getBigDecimalValue(drgsManageInfo.get("localDRGsGroupTotalWeight"));
						record.put("local_drgs_group_code",localDRGsCode);
						if(localDRGsGroupTotalWeight != null){
							record.put("local_drgs_group_total_weight",NumberUtils.getString(localDRGsGroupTotalWeight, 3));
						}else{
							record.put("local_drgs_group_total_weight",null);
						}
						String whetherMDTName = ObjectUtils.getStringValue(drgsManageInfo.get("whetherMDTName"));
						record.put("mdt_code",whetherMDTName);
					}else{
						record.put("mdt_code","否");
					}

				}
				record.put("medical_resource_cost",medicalResourceCost.floatValue()+"");




				records.add(record);
			}
			ExcelUtils.exportExcel1(out,headers, keys, records);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@PostMapping(value = "/import_drgs_group")
	public String importDRGsGroup(@RequestParam("uploadFiles")MultipartFile[] uploadFiles,HttpServletRequest request) {
		try{
			if(uploadFiles!=null && uploadFiles.length>0){
				MultipartFile uploadFile = uploadFiles[0];
				Workbook workbook = WorkbookFactory.create(uploadFile.getInputStream());
				Sheet sheet = workbook.getSheetAt(0);
				List<DRGsManageInfo> drgsManageInfos = new ArrayList<DRGsManageInfo>();
				int rowIndex = 0;
				for (Row row : sheet) {
					rowIndex ++;
					if(rowIndex ==1){
						continue;
					}
					DRGsManageInfo drgsManageInfo = new DRGsManageInfo();
					short minColIx = row.getFirstCellNum();
					short maxColIx = row.getLastCellNum();
					for(short colIx=minColIx; colIx<maxColIx; colIx++) {
					  Cell cell = row.getCell(colIx);
					  if(cell == null) {
					    continue;
					  }
					  //String value =ExcelUtils.getStringValue(cell);
					  String value = cell.getStringCellValue();
					  if(value != null && colIx+1 ==1){
							drgsManageInfo.setOnlyId(value);
						}else if(value != null && colIx+1 ==13){
							BigDecimal useVentilatorNumberOfHour = new BigDecimal(value);
							drgsManageInfo.setUseVentilatorNumberOfHour(useVentilatorNumberOfHour);
						}else if(value != null && colIx+1 ==14){
							BigDecimal icuNumberOfDay = new BigDecimal(value);
							drgsManageInfo.setIcuNumberOfDay(icuNumberOfDay);
						}else if(value != null && colIx+1 ==15){
							drgsManageInfo.setLocalDRGsCode(value);
						}else if(value != null && colIx+1 ==16){
							BigDecimal localDRGsGroupTotalWeight = new BigDecimal(value);
							drgsManageInfo.setLocalDRGsGroupTotalWeight(localDRGsGroupTotalWeight);
						}
						else if(value != null && colIx+1 ==17){
							drgsManageInfo.setWhetherMDTName(value);
						}
					}

					drgsManageInfos.add(drgsManageInfo);
				}
				List<String> emptyGroups =new ArrayList<String>();
				for (DRGsManageInfo drgsManageInfo : drgsManageInfos) {
					List<Map<String,Object>> drgsGroups = baseInfoService.getDRGsGroupByQueryName(drgsManageInfo.getLocalDRGsCode());
					if(drgsGroups.isEmpty()){
						String localDRGsCode = drgsManageInfo.getLocalDRGsCode().toUpperCase();
						if(!emptyGroups.contains(localDRGsCode)){
							emptyGroups.add(drgsManageInfo.getLocalDRGsCode());
						}

					}
				}
				if(!emptyGroups.isEmpty()){
					StringBuilder emptyStrs = new StringBuilder();
					int index = 0;
					for (String emptyGroup : emptyGroups) {
						if(index != 0){
							emptyStrs.append(",");
						}
						index++;
						emptyStrs.append(emptyGroup);
					}
					return "redirect:/drgs_manage/import_drgs_group_page?resultCode=0&emptyGroups="+emptyStrs.toString();
				}
				medicalRecordDRGsService.uploadDRGsGroup(drgsManageInfos);
				return "redirect:/drgs_manage/import_drgs_group_page?resultCode=1";
			}else{
				return "redirect:/drgs_manage/import_drgs_group_page?resultCode=0";
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "redirect:/drgs_manage/import_drgs_group_page?resultCode=-1";
		}

	}

	private BigDecimal getBigDecimalValue(Object obj){
		if(obj == null){
			return null;
		}
		if(obj instanceof BigDecimal){
			return (BigDecimal)obj;
		}else if(obj instanceof Double){
			return new BigDecimal((Double)obj);
		}
		else if(obj instanceof Integer){
			return new BigDecimal((Integer)obj);
		}
		else if(obj instanceof String){
			return new BigDecimal((String)obj);
		}
		else{
			return null;
		}
	}

	private Integer getIntegerValue(Object obj){
		if(obj instanceof Integer){
			return new Double((Integer)obj).intValue();
		}else if(obj instanceof BigDecimal){
			return ((BigDecimal)obj).intValue();
		}else if(obj instanceof Long){
			return ((Long)obj).intValue();
		}else if(obj instanceof Long){
			return ((Double)obj).intValue();
		}else{
			return null;
		}
	}

}
